package me.lc.superDown.sprite.platforms;

import java.util.Timer;
import java.util.TimerTask;

import me.lc.superDown.core.GameMap;
import me.lc.superDown.core.GameSystem;
import me.lc.superDown.sprite.Platform;
import me.lc.superDown.util.AudioHelper;

import com.wiyun.engine.actions.Action.Callback;
import com.wiyun.engine.actions.Animate;
import com.wiyun.engine.actions.FadeTo;
import com.wiyun.engine.actions.Spawn;
import com.wiyun.engine.nodes.Animation;
import com.wiyun.engine.nodes.Sprite;
import com.wiyun.engine.types.WYRect;

public class BreakPlatform extends Platform {

	Sprite breakActionSp;

	private float width;
	private float height;

	Animation animationBreak;

	Timer breakTimer;

	@Override
	protected void createPlatformSprite() {
		sp = Sprite.make(GameSystem.tex_platformBreak);
		width = GameSystem.tex_platformBreakAction.getWidth() / 3.0f;
		height = GameSystem.tex_platformBreakAction.getHeight();
	}

	@Override
	public float getPlatformWidth() {
		return GameSystem.tex_platformBreak.getWidth();
	}

	@Override
	public void standPlatform() {
		breakTimer = new Timer();
		breakTimer.schedule(new TimerTask() {
			@Override
			public void run() {
				// 平台破碎,人物掉落
				breakActionSp = Sprite.make(GameSystem.tex_platformBreakAction,
						frameAt(0));
				BreakPlatform.this.addChild(breakActionSp);
				animationBreak = new Animation(0);
				animationBreak.addFrame(0.2f, frameAt(0), frameAt(1),
						frameAt(2));
				animationBreak.autoRelease();
				Animate animate1 = Animate.make(animationBreak);
				animate1.autoRelease();

				FadeTo animate2 = FadeTo.make(0.8f, 255, 0);
				Spawn spawn = Spawn.make(animate1, animate2);
				spawn.setCallback(new Callback() {
					@Override
					public void onUpdate(int arg0, float arg1) {
					}

					@Override
					public void onStop(int arg0) {
						breakActionSp.setVisible(false);
					}

					@Override
					public void onStart(int arg0) {
						sp.setVisible(false);
					}
				});
				breakActionSp.runAction(spawn);
				if (getTool() != null && !getTool().isHited) {
					getTool().setVisible(false);
				}

				// 人物掉落
				setCanStand(false);
				if (!isManLeaved()) {
					GameMap.instance.setOnPlatform(false);
				}
			}
		}, 400);

	}

	private WYRect frameAt(int index) {
		return WYRect.make(index * width, 0, width, height);
	}

	@Override
	public void leavePlatform() {
		setManLeaved(true);
	}

}
